//
//  CZUseraccountViewModel.swift
//  sinaWeiboswift
//
//  Created by 段文杰 on 16/4/11.
//  Copyright © 2016年 段文杰. All rights reserved.
//

import UIKit
import SVProgressHUD
class CZUseraccountViewModel: NSObject {
    
 
   static let sharInatance = CZUseraccountViewModel()
    
    override init() {
        super.init()
         userAccount = loadUserAccount()
        
    }
    var userAccount : CZAccountModel?
    var userLogin:Bool {
    
        get {
        
            return userAccount != nil
        
        }
    }
        
    
    
    // MARK: - ******************* AFNeworking ********************
    
    func loaderAcceseeToken(code : String, callBack: (error: NSError?) -> ()) {
        
        let URLString = accessTokenURLString
        let parameters = [
            "client_id": client_id,
            "client_secret": client_secret,
            "grant_type": grant_type,
            "code": code,
            "redirect_uri": redirect_uri
            
            
        ]
        /*"access_token" = "2.00jND_xB0G_w9H7d539d006bDVP5NB";
         "expires_in" = 110226;
         "remind_in" = 110226;
         uid = 1792477271;
         */
        CZNetWorkingTool.sharInstance.POST(URLString, parameters: parameters, progress: nil, success: { (task, response) in
            
            HMPrint(response)
            let result = response as? [String: AnyObject]
            if let dict = result {
                
                //赋值给属性

                self.userAccount = CZAccountModel(dict: dict)
            
                self.saveUserAccount()
//                self.loadUserAccount()
                
                HMPrint("成功获得accessToken\(self.userAccount)")
                //拼接路径
//                 let  pathfile = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last?.stringByAppendingString("/account.plist")
                
               
//                //拼接方法
//                NSKeyedArchiver.archiveRootObject(accountModel, toFile: self.pathfile!)
                
                //成功获取accessToken
                callBack(error: nil)
                
            }
            
            
        }) { (task, error) in
            HMPrint(error)
            //失败获取accessToken

            callBack(error: error)
        }
        
        
    }
    func saveUserAccount(){
    
        if let userAccount = self.userAccount {
            // 归档
            NSKeyedArchiver.archiveRootObject(userAccount, toFile: accountPath)
        }

    
    }
    
    @objc  func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    @objc func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
        SVProgressHUD.showErrorWithStatus("加载失败!")
        SVProgressHUD.setDefaultMaskType(.Custom
        )
    }
    //TODO:麻蛋这里很烦躁 啃起来不顺眼
    /// 从沙盒里面解档UserAccount对象
    func loadUserAccount() -> CZAccountModel? {
        
        // 解档账号,有可能有,有可能没有
        let userAccount = NSKeyedUnarchiver.unarchiveObjectWithFile(accountPath) as? CZAccountModel
        
        // 可选绑定, 判断账号是否有值,账号有值,判断是否过期
        // 测试过期时间,
        //        userAccount?.expiresDate = NSDate(timeIntervalSinceNow: -100)
        if let account = userAccount where account.expiresData?.compare(NSDate()) == NSComparisonResult.OrderedDescending {
            HMPrint("没有过期: \(account)")
            
            
            return account
        }
        
        return nil
    }

    func loadUserInfor(loadUserinfocallBack: (error: NSError?)->()){
    
        guard let access_token = userAccount?.access_token else{
        
            HMPrint("access_token没有值")
            let error = HMNetworkErrorEnum.AccessTokenEmpty.error()
                
            loadUserinfocallBack(error:error )
             return
        }
    
        guard let uid = userAccount?.uid else{
        
            HMPrint("uid没有值")
            let error = HMNetworkErrorEnum.AccessTokenEmpty.error()
            
            loadUserinfocallBack(error:error )
            return
        
        }
    
        // url
        let urlString = "https://api.weibo.com/2/users/show.json"
        
        // 参数
        let parameters = [
            "access_token" : access_token,
            "uid": uid
        ]

    CZNetWorkingTool.sharInstance.GET(urlString, parameters: parameters, progress: nil, success: { (task, responce) in
        
//        HMPrint("加载用户信息成功\(responce)")
        
        if let dict = responce as? [String: AnyObject] {
            // 将获取到得数据赋值给当前账号
            self.userAccount?.screen_name = dict["screen_name"] as? String
            self.userAccount?.avatar_large = dict["avatar_large"] as? String
            
            // 将当前对象保存到沙盒中
            self.saveUserAccount()
            
            loadUserinfocallBack(error: nil)
        
        }
        }) { (task, error) in
            
            HMPrint("加载用户数据失败\(error)")
            loadUserinfocallBack(error: error)
        }
        
    
    }

}
